#!/usr/bin/php
<?php

function isYear($year)
{
    if ($year % 400 == 0
        || $year % 4 == 0 && $year % 100 != 0)
        return true;
    return false;
}

const MONTH = [
    [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
    [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
];


function laterTime($start, $end)
{
    //间隔秒
    $sec = $end - $start;
    //间隔天
    $days = (int)($sec / 86400);
    //间隔时分秒
    $sec -= $days * 86400;

    //起始年
    $sy = date("Y", $start);

    $year = 0;

    echo "init days = ", $days, PHP_EOL;

    //按年减天，算出间隔年
    while ($days >= ($d = 365 + isYear($sy))) {
        $days -= $d;
        $sy++;
        $year++;
    }
    echo "ys = ", $sy, ", days = ", $days, PHP_EOL;
    $em = date("m", $end);

    //起始月
    $sm = date("m", $start) - 1;
    $y = isYear($sy);
    $month = 0;

    while ($days >= MONTH[$y][$sm]) {
        // echo $sm;
        $days -= MONTH[$y][$sm++];
        // echo ", ", $days, PHP_EOL;
        if ($sm > 11) {
            $y = isYear(++$sy);
            $sm = 0;
        }
        $month++;
    }

    $hour = (int)($sec / 3600);
    $sec -= $hour * 3600;
    // echo "sec = ", $sec, PHP_EOL;
    $min = (int)($sec / 60);
    $sec -= $min * 60;
    // echo "sec = ", $sec, PHP_EOL;

    return compact("year", "month", "days",
                   "hour", "min", "sec");
}

function outTime($dst, $now = null)
{
    if ($now === null)
        $now = time();

    if($now > $dst) {
        $interval = laterTime($dst, $now);
        $prefix = "已过";
    } else {
        $interval = laterTime($now, $dst);
        $prefix = "剩于";
    }

    return sprintf(
        "%s: %s 年 %d 月 %d 日 %d 小时 %d 分钟 %d 秒",
        $prefix,
        $interval['year'],
        $interval['month'],
        $interval['days'],
        $interval['hour'],
        $interval['min'],
        $interval['sec']
    );
}

function main($argc, & $argv)
{
    //起始月 <= 结束月
    //  起始日 > 结束日 +1
    //  起始日 <= 结束日
    //       并且起始月大于2, 需要判断闰年用下一年，所以会少减一天
    //
    // $now_date = "2016-12-10 09:44:10";
    // $target = "2015-01-15 09:44:10";
    $now_date = "2015-02-20 09:44:10";
    $target = "2016-03-29 09:44:10";
    /*
     * $content = file_get_contents("config");
     * preg_match("/.*date[\ ]+=[\ ]+(.*)/", $content, $m);
     * $target = $m[1];
     */

    echo "当前时间：", $now_date, PHP_EOL;
    echo "目标时间：", $target, PHP_EOL;
    // echo strtotime($target), PHP_EOL;
    $now = strtotime($now_date);
    $dst = strtotime($target);

    echo outTime($dst, $now), PHP_EOL;

    $d1 = new DateTime($now_date);
    $d2 = new DateTime($target);
    $d = $d1->diff($d2);

    $str = array("剩于", "已过");
    // print_r($d);

    printf("diff: %s: %d y %d m %d d %d H %d M %d S\n",
            $str[$d->invert], $d->y, $d->m, $d->d,
            $d->h, $d->i, $d->s);

    return 0;
}

exit(main($argc, $argv));

